
import random
from . import user_bp
from flask import current_app, request,render_template,redirect, session,url_for,abort,g,make_response,flash
from formodle import Award,Logininmd,Signupmd
from decoraters import isloginin
from models import Groupq, Userinfo,Articleq
from exts import db
from toolfunc import flash_form_error

@user_bp.route('/profile?<int:uid>',methods=["POST","GET"])
@isloginin
def profile(uid):
    form=Award()
    if request.method=="GET":
        user=Userinfo.query.filter(Userinfo.u_id==uid).first()
        group=Groupq.query.filter(Groupq.g_id==user.g_id).first()
        article=Articleq.query.filter(Articleq.u_id==uid).all()
        if user is not None:
            if user.g_id>13:
                nextexp="∞"
            else:
                nextexp=Userinfo.exp_need[user.g_id]-user.u_exp
            return render_template('profile.html',user=user,group=group,article=article,nextexp=nextexp,form=form)
    if request.method=="POST":
        if g.rid==9:
            user=Userinfo.query.filter(Userinfo.u_id==request.form.get('uid_select')).first()
            if user==None:
                flash("该用户不存在！")
            else:
                user.g_id=request.form.get("ftm")
                db.session.commit()
                flash("修改成功！")
        else:
            flash("权限不足！")
        
        return redirect(url_for("user.profile",uid=uid))

@user_bp.route('/loginin', methods=['POST', 'GET'])
def loginin():
    forms=Logininmd()
    if request.method == 'GET':
        return render_template('loginin.html',form=forms)
    elif request.method == 'POST':
        #if(request.form['username'] == 'admin') and (request.form['password'] == 'Hts@9527') and forms.validate_on_submit():
        if forms.validate_on_submit():
            upwd=Userinfo.query.filter(Userinfo.u_name==request.form['username']).first()
            if upwd is not None and upwd.check_pwd(request.form['password']):
                session['username']=request.form['username']
                session['uid']=upwd.u_id
                gid=upwd.g_id
                session['rid']=db.session.query(Groupq.g_rid).filter(Groupq.g_id==gid).first()[0]
                
                resp=make_response(redirect(url_for('root.index')))
                resp.set_cookie("username",request.form['username'])
                return resp
            else:
                flash("用户名或密码错误")
                return redirect(url_for("user.loginin")) 
                        
        else:
            flash_form_error(form=forms)
            return redirect(url_for("user.loginin")) 

    else:
        abort(404)


@user_bp.route('/signup', methods=['GET', 'POST'])
def signup():
    qa=current_app.config.get('Q_AND_A')    #从配置中加载验证问题和答案，推荐不写在配置而是写在数据库里————但我懒得搞了
    forms = Signupmd()
    if request.method == 'GET':
        ques=random.randint(0,len(qa)-1)
        g.quse=ques
        return render_template('signup.html', form=forms,qa=qa,ques=ques)
    if request.method == 'POST':
        if forms.validate_on_submit():
            username=request.form.get('username')
            password=request.form.get('password')
            mail=request.form.get('mail')
            ans1=request.form.get('ques1')
            if ans1!=qa[int(request.form.get('ques'))][1]:
                flash("不会吧不会吧不会有人这么简单的问题都不会吧？")
                return redirect(url_for("user.signup"))
            if Userinfo.query.filter(Userinfo.u_name==username).first() is not None:
                flash("用户名已存在")
                return redirect(url_for("user.signup"))
            if Userinfo.query.filter(Userinfo.u_mail==mail).first() is not None:
                flash("邮箱已使用")
                return redirect(url_for("user.signup"))
            img=url_for("static",filename="img/default0{}.jpg".format(random.randint(1,10)))
            newobj=Userinfo(u_name=username,u_mail=mail,g_id=1,u_img=img,u_exp=0)
            newobj.set_pwd(password)
            db.session.add(newobj)
            db.session.commit()
            flash("注册成功")
            return redirect(url_for("user.loginin"))
        else:
            flash_form_error(forms)          
            return redirect(url_for("user.signup"))
    else:
        abort(404)

@user_bp.route('/logout')
@isloginin
def logout():
    g.username=None
    session.clear()
    resp=redirect(url_for('root.index'))
    resp.delete_cookie('username')
    return resp 

@user_bp.route('/session')
@isloginin
def getsession():

    return str(session)

